package com.weme.live.view

import android.content.Context
import android.graphics.Color
import android.os.CountDownTimer
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import com.weme.common.util.gone
import com.weme.common.util.visible
import com.weme.live.databinding.LayoutTaskCountdownBinding
import io.reactivex.disposables.Disposable

class CountdownView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyle: Int = 0) : FrameLayout(context, attributeSet, defStyle) {


    private val viewBinding = LayoutTaskCountdownBinding.inflate(LayoutInflater.from(context), this, true)
    private var disposable: Disposable? = null
    var isStartTime = false
    var countDownTimer : MyCountDownTimer?=null

    //匹配倒计时
    fun setCountdownTime(seconds: Long) {
        if (isStartTime) {
            return
        }
        isStartTime = true
        viewBinding.imLock.gone()
        viewBinding.tvLiveTime.gone()
        viewBinding.lastTimeView.visible()

        viewBinding.lastTimeView.start()
        viewBinding.lastTimeView.apply {
            radius = 25F
            lineColor = Color.parseColor("#FAFF0D")
            lineWidth = 5F
            duration = seconds.toInt()
            prepare()
        }

         countDownTimer = MyCountDownTimer(seconds * 1000, 1000, object : MyCountDownTimer.CountDownListener {
            override fun onTick(secondsRemaining: Long) { // 在倒计时过程中执行的操作
                println("倒计时剩余时间：$secondsRemaining 秒")
                viewBinding.llTime.visible()
                viewBinding.tvTime.text = String.format(secondsRemaining.toString() + "s")
            }

            override fun onFinish() { // 倒计时完成后执行的操作
                println("倒计时完成")
                viewBinding.llTime.gone()
            }
        })

        // 启动倒计时
        countDownTimer?.start()

    }

    class MyCountDownTimer(totalMillis: Long, private val intervalMillis: Long, private val listener: CountDownListener) : CountDownTimer(totalMillis, intervalMillis) {

        override fun onTick(millisUntilFinished: Long) {
            val secondsRemaining = millisUntilFinished / 1000
            listener.onTick(secondsRemaining)
        }

        override fun onFinish() {
            listener.onFinish()
        }

        interface CountDownListener {
            fun onTick(secondsRemaining: Long)
            fun onFinish()
        }
    }

    //正常倒计时
    fun updateTime(seconds: Long) {
        if (viewBinding.imLock.visibility == View.GONE) {
            viewBinding.imLock.visible()
            viewBinding.tvLiveTime.visible()
            viewBinding.lastTimeView.gone()
        }
        viewBinding.tvLiveTime.text = String.format("%02d:%02d", seconds / 60, seconds % 60)
    }


    fun onCloneView() {
        disposable?.dispose()
        countDownTimer?.cancel()
        countDownTimer?.onFinish()
    }
}